// src/utils/request.js
import axios from 'axios';
import qs from 'qs';
// import { useGlobalLoading } from './request/useGlobalLoading';
import { ResultEnum } from '@/enums';
import { getCurrentLanguage } from '@/lang';
import { getToken } from '@/utils/authToken';
import { errorHandler } from './request/errorHandler';
import { handleTokenRefresh } from './request/handleTokenRefresh';
import { handleRequestData } from './request/encryptHandle';
import { installHandle } from './request/installHandle';

// 请求独立过渡效果（默认不使用，而是使用组件内置过渡效果）
// const { showLoading, hideLoading } = useGlobalLoading();

const getBaseURL = () => {
  // ... (逻辑不变)
  if (import.meta.env.MODE === 'development') return '/admin';
  if (import.meta.env.MODE === 'production') {
    const api = import.meta.env.VITE_APP_BASE_API;
    return (api || window.location.origin) + '/admin';
  }
  return '';
};

const service = axios.create({
  baseURL: getBaseURL(),
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
  paramsSerializer: (params) => qs.stringify(params),
});

// 存储加密字段
let lastEncryptFields = null;

// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    //showLoading();
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    config.headers['Accept-Language'] =
      getCurrentLanguage() || navigator.language || 'zh-CN';

    config.data = await handleRequestData(config.data, lastEncryptFields);
    return config;
  },
  (error) => {
    //hideLoading();
    Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  // onFulfilled: 处理 HTTP 2xx 响应
  async (response) => {
    //hideLoading();

    // 获取响应数据开发期间使用
    if (import.meta.env.MODE === 'development') {
      console.log(
        'RESPONSE：',
        response.config.method,
        response.config.url,
        response.config.data ?? response.config.params ?? 'no params',
        response.data ? response.data : 'no data',
      );
    }

    // 从响应头中获取 X-Fields-Encrypt
    const currentEncryptFields = response.headers['x-fields-encrypt'];
    if (currentEncryptFields) {
      lastEncryptFields = JSON.parse(currentEncryptFields);
    }

    // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'），如果是，直接返回二进制流
    if (
      response.config.responseType === 'blob' ||
      response.config.responseType === 'arraybuffer'
    ) {
      return response;
    }

    const { success, code, data, message } = response.data;

    switch (code) {
      case ResultEnum.SUCCESS:
        return { success, code, data, message };

      // 令牌过期
      case ResultEnum.TOKEN_EXPIRED: // 200008
        return handleTokenRefresh(response.config);

      // 登录失效
      case ResultEnum.TOKEN_INVALID: // 200011
      case ResultEnum.TOKEN_DISABLED: // 200009
      case ResultEnum.REFRESH_EXPIRED: // 200012
      case ResultEnum.REFRESH_DISABLED: // 200013
        return errorHandler.handleSessionExpired(message);

      // 未安装
      case ResultEnum.E_SYS_SYSTEM_NOT_INSTALL: // 100005
        return installHandle(message);

      default:
        return errorHandler.handleBusinessError({
          success,
          code,
          data,
          message,
        });
    }
  },
  // onRejected: 处理非 HTTP 2xx 响应
  async (error) => {
    //hideLoading();
    console.error('Request error:', error);
    // 其他所有HTTP错误，交由errorHandler处理
    return errorHandler.handleHttpError(error);
  },
);

export default service;
